package com.example.treehole.ui.page.postDetail

import androidx.lifecycle.ViewModel
import com.example.treehole.service.DataRepository
import com.example.treehole.ui.component.toCommentType
import com.example.treehole.ui.model.Comment
import com.example.treehole.ui.model.CommentToPost
import com.example.treehole.ui.model.CommentType
import com.example.treehole.ui.model.PostDetail
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

class PostDetailViewModel : ViewModel() {
    private val _postDetail = MutableStateFlow<PostDetail?>(null)
    val postDetail: StateFlow<PostDetail?> = _postDetail

    private val _postId = MutableStateFlow<Int>(0)
    val postId: StateFlow<Int> = _postId

    fun updatePostDetail(postDetail: PostDetail?) {
        _postDetail.value = postDetail
    }

    fun updateCommenting(state: Boolean) {
        _postDetail.value?.isComment = state
    }

    fun updatePostId(id: Int) {
        _postId.value = id
    }

    // 直接将comment加入到postDetail中
    fun addNewComment(comment: Comment) {
        if (comment.type.toCommentType() == CommentType.CommentToPost) {
            val newComment: CommentToPost = CommentToPost.fromComment(comment)
            _postDetail.value?.cmtList?.add(0, newComment)
        } else if (comment.type.toCommentType() == CommentType.CommentToComment) {
            _postDetail.value?.cmtList?.forEach { item ->
                if (item.cmtId == comment.cmtCmtId) {
                    item.replyList.add(comment)
                }
            }
        }
    }

    suspend fun getPostDetail(
        jwlToken: String,
        postId: Int,
        userId: Int
    ) {
//        updatePostDetail(null)
        updatePostId(postId)
        val res = DataRepository.askPostDetail(jwlToken, postId, userId)
        res?.let {
            updatePostDetail(it)
        }
    }

    suspend fun getPostDetailById(
        jwlToken: String,
        userId: Int
    ) {
        val res = DataRepository.askPostDetail(jwlToken, postId.value, userId)
        res?.let {
            updatePostDetail(it)
        }
    }
}